package signal;

import java.util.Stack;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Pot {

    private Stack<Integer> pot = new Stack<Integer>();
    public static final int MAX_NUMBER = 100; //妈妈一共做100个馒头，程序就结束了。

    public volatile static int COUNT = 0;
    public static final int MAX_LEN = 10;

    private final ReentrantLock lock = new ReentrantLock();
    private Condition noCake = lock.newCondition(); //锅里没有馒头的条件
    private Condition fullCake = lock.newCondition(); //锅馒头做满时的条件

    private int bigSonNum; //大儿子吃的数量
    private int smallSonNum; //小儿子吃的数量

    public Stack<Integer> getPot() {
        return pot;
    }

    public ReentrantLock getLock() {
        return lock;
    }

    public Condition getNoCake() {
        return noCake;
    }

    public void setFullCake(Condition fullCake) {
        this.fullCake = fullCake;
    }

    //锅里面取馒头的方法
    public void eatCake(String name) { // 消费者从锅里面取馒头

        try {
            if (pot.size() <= 0 && Pot.COUNT < 100) {
                System.out.println(name + "锅空了，等待妈妈做馒头！");
                noCake.await(); // wait();
            }
            if (pot.size() > 0) {
                System.out.println(name + ",吃了第" + pot.pop() + "个馒头");
                if ("大林".equals(name)) {
                    this.bigSonNum++;
                } else {
                    this.smallSonNum++;
                }
                fullCake.signalAll(); // notify();

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {

        }
    }

    //做馒头的方法
    public void makeCake() {
        try {
            if (pot.size() >= Pot.MAX_LEN) {
                System.out.println("妈妈：锅已满了，等待儿子吃馒头！");
                fullCake.await(); // wait();
            }
            if (Pot.COUNT < 100) {
                Pot.COUNT++;
                pot.push(Pot.COUNT);
                System.out.println("妈妈做了第" + Pot.COUNT + "个馒头");
                noCake.signalAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
        }
    }

    //显示结果
    public void showResult() {
        System.out.println("大林吃了：" + bigSonNum + "个馒头!");
        System.out.println("小林吃了：" + smallSonNum + "个馒头！");
    }
}
